package cn.mymall.web.controller;

import cn.mymall.config.SpringContextUtil;
import cn.mymall.constant.CachedCont;
import cn.mymall.constant.StatusConstant;
import cn.mymall.entity.Member;
import cn.mymall.redis.RedisHelper;
import cn.mymall.sec.MessageDigestUtil;
import cn.mymall.service.IMemberService;
import cn.mymall.support.ResultCode;
import cn.mymall.util.BaseWebUtil;
import cn.mymall.util.RandomUtil;
import freemarker.template.utility.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Controller
@Slf4j
public class LoginController extends BaseController {
    @Autowired
    private IMemberService memberService;
    @Autowired
    private RedisHelper redisHelper;

    @RequestMapping("/login")
    public String login() {
        return "front/login.ftl";
    }

    protected String getMobileCodeKey(String mobile) {
        return "mobile_login_" + mobile;
    }

    @RequestMapping("/loginValidate")
    @ResponseBody
    public ResultCode loginValidate(String mobile, String code, HttpServletResponse response, HttpServletRequest request) {
        if (StringUtils.isBlank(mobile)) {
            return ResultCode.getFailure("请输入手机号！");
        }
        if (StringUtils.isBlank(code)) {
            return ResultCode.getFailure("请输入手机验证码！");
        }
        String ckname = getMobileCodeKey(mobile);
        String str = (String) redisHelper.get(ckname);
        if (StringUtils.isBlank(str)) {
            return ResultCode.getFailure("验证码不存在或已过期");
        }
        String ip = BaseWebUtil.getRemoteIp(request);
        if (!StringUtils.equalsIgnoreCase(code, str)) {
            log.warn("验证码错误：" + mobile + ",ip:" + ip);
            return ResultCode.getFailure("验证码错误");
        }
        Member member = memberService.getMemberByMobile(mobile);
        if (member == null) {
            member = new Member();
            member.setStatus(StatusConstant.Y);
            member.setMobile(mobile);
            member.setNickname(mobile.substring(0, 4) + "****" + mobile.substring(8));
            member.setAddTime(LocalDateTime.now());
            member.setModifyTime(member.getAddTime());
            memberService.saveOrUpdate(member);
        }
        if (!member.isValid()) {
            return ResultCode.getFailure("账户已禁止登陆！");
        }
        String token = RandomUtil.getLowerRandomString(32);
        redisHelper.set(token, member.getId(), CachedCont.ONE_DAY * 7);
        addCookie(response, "token", token, "/", CachedCont.ONE_DAY * 7);
        return ResultCode.SUCCESS;
    }


    public void addCookie(HttpServletResponse response, String cookiename, String cookievalue, String path, int maxSecond) {
        Cookie cookie = new Cookie(cookiename, cookievalue);
        cookie.setPath(path);
        cookie.setMaxAge(maxSecond);
        cookie.setHttpOnly(false);
        response.addCookie(cookie);
    }

    @RequestMapping("/getCode")
    @ResponseBody
    public ResultCode getCode(String mobile, HttpServletRequest request) {
        String code = RandomUtil.getDigitalRandomString(6);
        code = "888888";
        redisHelper.set(getMobileCodeKey(mobile), code, 600);
        //TODO模拟发送手机号验证码给用户
        log.warn("mobile->{},code->{}", mobile, code);
        return ResultCode.SUCCESS;
    }

    @RequestMapping("/logout")
    public String exit(String lastpage, ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = BaseWebUtil.getCookie(request, "token");
        model.put("lastpage", lastpage);
        if (cookie == null) {
            return login();
        }
        String ut = cookie.getValue();
        BaseWebUtil.clearCookie(response, "/", "token");
        return login();
    }

    @RequestMapping("/isLogin")
    @ResponseBody
    public ResultCode isLogin(HttpServletRequest request){
        Cookie cookie = WebUtils.getCookie(request, "token");
        if (cookie == null) {
            return ResultCode.getFailure("unLogin");
        }
        String ut = cookie.getValue();
        Integer id = (Integer)redisHelper.get(ut);
        if (id==null) {
            return ResultCode.getFailure("unLogin");
        }
        Member member = memberService.getById(id);
        if (member == null) {
            return ResultCode.getFailure("unLogin");
        }
        return ResultCode.SUCCESS;
    }
}
